package com.leyou.order.listener;

import com.leyou.client.user.UserClient;
import com.leyou.common.auth.pojo.UserHolder;
import com.leyou.common.auth.pojo.UserInfo;
import com.leyou.common.constants.MQConstants;
import com.leyou.order.dto.CartDTO;
import com.leyou.order.dto.OrderDTO;
import com.leyou.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 商品上下架消息监听
 */
@Component
@Slf4j
public class OrderListener {
    @Autowired
    private OrderService orderService;
    @Autowired
    private UserClient userClient;

    /**
     * 监听秒杀消息
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MQConstants.Queue.SECOND_SECKILL_QUEUE),
            exchange = @Exchange(name = MQConstants.Exchange.SECOND_EXCHANGE_NAME, type = ExchangeTypes.TOPIC),
            key = MQConstants.RoutingKey.SECOND_SECKILL_KEY
    ))

    public void createStaticPage(String skuIdAndUserid){
        String[] split = skuIdAndUserid.split(",");
        String skuId = split[0];
        String userId = split[1];
        OrderDTO orderDTO = new OrderDTO();
        orderDTO.setAddressId(1l);
        orderDTO.setPaymentType(1);
        List<CartDTO> carts = new ArrayList<>();
        CartDTO cartDTO = new CartDTO();
        cartDTO.setSkuId(Long.valueOf(skuId));
        cartDTO.setNum(1);
        carts.add(cartDTO);
        orderDTO.setCarts(carts);
        UserInfo userInfo = new UserInfo(32l, "admin", "adimn");
        UserHolder.setUser(userInfo);
        Long aLong = orderService.buildOrder(orderDTO);
        log.info("【秒杀商品】秒杀成功，生成订单" + aLong);
    }

}
